import os
import ConfigParser
from rsa import RSA_ROOT

class ConfigLoader(object):
    """
    Load the configuration preferences of the user
    """
       
    sections = ["Rules", "Configuration"]
    options = ["include", "exclude"]
    location = os.path.join(RSA_ROOT, "resources/rsa.cfg")
        
    config = ConfigParser.RawConfigParser()
    
    def get_preferences(self, section, option):
        pref = self.config.get(section, option)
        if(len(pref) == 0):
            return None
        return pref.split(',')

    def load(self, configfile):
        """
        Load all the preferences set in the configuration file. Such as: used rules, 
        ignored rules, printing, etc
        """
        # if configuration file doesn't exist return
        if(not os.path.exists(configfile)): return (None, None, None)
        # load configuration file
        include = exclude = rsconfig = None
        self.config.read(configfile)
        if(self.config.has_option(self.sections[0], self.options[0])):
            include = self.get_preferences(self.sections[0], self.options[0])
        if(self.config.has_option(self.sections[0], self.options[1])):
            exclude = self.get_preferences(self.sections[0], self.options[1])
        if(self.config.has_section(self.sections[1])):
            rsconfig = {}
            for section in self.config.items(self.sections[1]):
                rsconfig[section[0]] = section[1]
        # return preferences as a list
        return (include, exclude, rsconfig)
    
    def save(self, include_rules=None, location=None):
        '''Save the selected rules to include in the analysis'''
        if(not location):
            location = self.location
        if(include_rules):
            dir = location[:location.rfind("/")]
            if not os.path.exists(dir):
                os.makedirs(dir)
            fp = file(location, 'w')
            value = ""
            for rule in include_rules:
                value = value + rule + ","
            self.config.set(self.sections[0], self.options[0], value[:-1])
            self.config.set(self.sections[0], self.options[1], "")
            self.config.write(fp)
    
    def save_conf(self, rule, value, location=None):
        '''Save the property, entered by the user, of a rule'''
        if(not location):
            location = self.location
        if(rule):
            dir = location[:location.rfind("/")]
            if not os.path.exists(dir):
                os.makedirs(dir)
            fp = file(location, 'w')
            self.config.set(self.sections[1], rule.lower(), value)
            self.config.write(fp)
    
    def load_preferences(self, location=None):
        """
        Load (if exists) the static analyzer configuration preferences of the user
        """
        if(not location):
            location = self.location
        return self.load(location)
